package com.cavy.platform.server.service;

import com.cavy.platform.server.domain.job.*;
import com.cavy.platform.server.repository.JobRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class JobTimeOutScanner {
    private static final int FIXED_RATE = 1000 * 60;
    @Autowired
    private JobRepository repository;

    @Scheduled(fixedRate = FIXED_RATE)
    public void heartbeatCheck() {
        // TODO: 性能需要改进，需要过滤已经结束的，错误的，已经超时的
        log.debug("开始job超时检查...");
        Date date = new Date();
        List<JobAction> list = repository.list();
        for (JobAction action : list) {
            if (action instanceof EndJob || action instanceof ErrorJob
                    || action instanceof TimeoutErrorJob) {
                continue;
            }
            Date runningTimeOut = action.getJob().getRunningTimeOut();
            boolean after = runningTimeOut.after(date);
            if (!after) {
                Job job = action.getJob();
                TimeoutErrorJob timeoutErrorJob = new TimeoutErrorJob(job);
                timeoutErrorJob.save();
                log.debug("工作空间:{},项目:{},流水线:{},job:{},已经设置为超时", job.getWorkspaceName(),
                        job.getProjectName(), job.getPipelineName(), job.getNumber());
            }
        }
        log.debug("job超时检查完成");
    }
}
